package com.experiment.springboot_experiment3.service;

import com.experiment.springboot_experiment3.pojo.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;


@Service
public class GetDataService {

    final  String URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    public List<RegionStats> regionStatsList = new ArrayList<>();

    @Scheduled(cron = "${chen.Schedules.updateVirusDataCron}")
    @PostConstruct
    public void fetchCoronaVirusData() throws IOException {
        //爬取csv文件
        RequestEntity<Void> requestEntity = RequestEntity
                                                .get(URI.create(URL))
                                                .headers(httpsHeaders -> httpsHeaders.add("User-Agent", "陈钿"))
                                                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();


        //解析csv文件
        if (body != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(body.getInputStream(), "UTF-8");
            CSVParser parser = new CSVParser(inputStreamReader, CSVFormat.EXCEL.withHeader());
            regionStatsList.clear();
            for (CSVRecord record : parser) {
                regionStatsList.add(RegionStats.builder()
                        .state(record.get("Province/State"))
                        .country(record.get("Country/Region"))
                        .latestTotalCases(Integer.parseInt(record.get(record.size() - 1)))
                        .diffFromPrevDay(Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)))
                        .build());
            }
        }
    }

}
